56D - Changing a String - CodeForces Solution


dp *2100

Please click on ads to support us..

C++ Code:

//https://codeforces.com/contest/56/problem/D
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define PI acos(-1)
#define LSB(i) ((i) & -(i))
#define ll long long
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define sc second
#define th third
#define fo fourth
#define pii pair<int,int>
#define pll pair<ll,ll>
#define ldb double
#define INF 1e15
#define MOD 1000000007
#define endl "\n"

#define all(data)       data.begin(),data.end()
#define TYPEMAX(type)   std::numeric_limits<type>::max()
#define TYPEMIN(type)   std::numeric_limits<type>::min()
#define MAXN 1007
ll dp[MAXN][MAXN];
char s[MAXN],t[MAXN];
int main()
{
    ios::sync_with_stdio(false); cin.tie(0);
    string a,b; cin>>a>>b;
    ll n=a.size(),m=b.size();
    for(int i=1;i<=n;i++) s[i]=a[i-1];
    for(int i=1;i<=m;i++) t[i]=b[i-1];
    for(int i=0;i<=n;i++)
    {
        for(int j=0;j<=m;j++) dp[i][j]=INF;
    }
    for(int i=0;i<=n;i++) dp[i][0]=i;
    for(int j=0;j<=m;j++) dp[0][j]=j;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++) dp[i][j]=min({dp[i][j],dp[i-1][j-1]+(ll)(s[i]!=t[j]),dp[i-1][j]+1,dp[i][j-1]+1});
    }
    cout<<dp[n][m]<<endl;
    ll i=n,j=m;
    while(i || j)
    {
        if(i && j && dp[i][j]==dp[i-1][j-1]+(ll)(s[i]!=t[j]) && s[i]!=t[j]) {cout<<"REPLACE "<<i<<" "<<t[j]<<endl; i--; j--;}
        if(i && j && dp[i][j]==dp[i-1][j-1]+(ll)(s[i]!=t[j]) && s[i]==t[j]) {i--; j--;}
        else if(i && dp[i][j]==dp[i-1][j]+1) {cout<<"DELETE "<<i<<endl; i--;}
        else if(j && dp[i][j]==dp[i][j-1]+1) {cout<<"INSERT "<<i+1<<" "<<t[j]<<endl; j--;}
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

162. Find Peak Element
1529A - Eshag Loves Big Arrays
19. Remove Nth Node From End of List
925. Long Pressed Name
1051. Height Checker
695. Max Area of Island
402. Remove K Digits
97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function
1920. Build Array from Permutation
494. Target Sum
797. All Paths From Source to Target
1547B - Alphabetical Strings
1550A - Find The Array
118B - Present from Lena
27A - Next Test
785. Is Graph Bipartite
90. Subsets II
1560A - Dislike of Threes
36. Valid Sudoku
557. Reverse Words in a String III
566. Reshape the Matrix
167. Two Sum II - Input array is sorted